package etnorservice.etnor_service.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import etnorservice.etnor_service.domain.dto.WebSocketMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class DeployWebSocketHandler extends TextWebSocketHandler {

    private final ObjectMapper objectMapper;
    private final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    public DeployWebSocketHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String deployId = getDeployId(session);
        sessions.put(deployId, session);
        log.info("WebSocket连接建立: {}", deployId);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        String deployId = getDeployId(session);
        sessions.remove(deployId);
        log.info("WebSocket连接关闭: {}", deployId);
    }

    public void sendMessage(String deployId, WebSocketMessage message) {
        WebSocketSession session = sessions.get(deployId);
        if (session != null && session.isOpen()) {
            try {
                String messageText = objectMapper.writeValueAsString(message);
                session.sendMessage(new TextMessage(messageText));
            } catch (IOException e) {
                log.error("发送WebSocket消息失败", e);
            }
        }
    }

    private String getDeployId(WebSocketSession session) {
        String path = session.getUri().getPath();
        return path.substring(path.lastIndexOf('/') + 1);
    }
}